package com.example.socialview.slice;

import com.example.socialview.ResourceTable;
import com.hendraanggrian.appcompat.widget.SocialView;
import com.hendraanggrian.appcompat.widget.Hashtag;
import com.hendraanggrian.appcompat.widget.ArrayProvider;
import com.hendraanggrian.appcompat.widget.Mention;
import com.hendraanggrian.appcompat.widget.SocialViewHelper;
import com.hendraanggrian.appcompat.widget.HashtagArrayAdapter;
import com.hendraanggrian.appcompat.widget.MentionArrayAdapter;
import com.hendraanggrian.appcompat.widget.SocialArrayAdapter;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.TextField;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Image;
import ohos.agp.components.Checkbox;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Text;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextTool;
import ohos.agp.window.dialog.BaseDialog;
import ohos.agp.window.dialog.PopupDialog;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import java.io.IOException;

/**
 * ex.
 *
 * @author zh
 * @since 2021-06-22
 */
public class MainAbilitySlice extends AbilitySlice {
    private SocialView helper;
    private static final String HASHTAG1 = "follow";
    private static final String HASHTAG2 = "followme";
    private static final String HASHTAG3 = "followmeorillkillyou";
    private static final int HASHTAG2_COUNT = 1000;
    private static final int HASHTAG3_COUNT = 500;
    private static final String MENTION1_USERNAME = "dirtyhobo";
    private static final String MENTION2_USERNAME = "hobo";
    private static final String MENTION3_USERNAME = "hendraanggrian";
    private static final String MENTION2_DISPLAYNAME = "Regular Hobo";
    private static final String MENTION3_DISPLAYNAME = "Hendra Anggrian";
    private ArrayProvider<Hashtag> defaultHashtagAdapter;
    private ArrayProvider<Mention> defaultMentionAdapter;
    private ArrayProvider<Person> customHashtagAdapter;
    private ArrayProvider<Person> customMentionAdapter;
    private TextField textView;
    private Component lineName;
    private ListContainer listContainer;
    private ArrayProvider hashtagAdapter;
    private ArrayProvider mentionAdapter;
    private int starts;
    private Component dialogView;
    private PopupDialog popupDialog;
    private Image more;
    private Image more1;
    private boolean isCustom = true;
    private boolean isHashtag = true;
    private boolean isMention = true;
    private boolean isHyperlink = true;

    @Override
    public void onStart(Intent intent) {
        try {
            int color = getResourceManager().getElement(ResourceTable.Color_status_bar_color).getColor();
            getWindow().setStatusBarColor(color);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        }
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        textView = (TextField) findComponentById(ResourceTable.Id_textView);
        more = (Image) findComponentById(ResourceTable.Id_more);
        more1 = (Image) findComponentById(ResourceTable.Id_more1);
        lineName = findComponentById(ResourceTable.Id_lineName);
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_listview);
        helper = SocialViewHelper.install(textView);
        textView.addTextObserver(textWatcher);
        defaultHashtagAdapter = new HashtagArrayAdapter(this);
        defaultMentionAdapter = new MentionArrayAdapter(this);
        customHashtagAdapter = new PersonAdapter(this);
        customMentionAdapter = new PersonAdapter(this);
        hashtagAdapter = defaultHashtagAdapter;
        mentionAdapter = defaultMentionAdapter;
        listContainer.setItemClickedListener((listContainer, component, i, l) -> {
            listContainer.setVisibility(Component.HIDE);
            if (listContainer.getItemProvider() == hashtagAdapter) {
                if (isCustom) {
                    Hashtag hashtag = (Hashtag) hashtagAdapter.getItem(i);
                    textView.delete(textView.getText().length() - starts, false, starts);
                    textView.append(helper.terminateToken(hashtag.getId()).toString());
                } else {
                    Person mention = (Person) hashtagAdapter.getItem(i);
                    textView.delete(textView.getText().length() - starts, false, starts);
                    textView.append(helper.terminateToken(mention.toString()).toString());
                }
            } else if (listContainer.getItemProvider() == mentionAdapter) {
                if (isCustom) {
                    Mention mention = (Mention) mentionAdapter.getItem(i);
                    textView.delete(textView.getText().length() - starts, false, starts);
                    textView.append(helper.terminateToken(mention.getUsername()).toString());
                } else {
                    Person mention = (Person) mentionAdapter.getItem(i);
                    textView.delete(textView.getText().length() - starts, false, starts);
                    textView.append(helper.terminateToken(mention.toString()).toString());
                }
            }
        });
        more.setClickedListener(component -> setShowDialog());
        textView.setClickedListener(component -> {
            ShapeElement element = new ShapeElement();
            element.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor("#00FFFF")));
            lineName.setBackground(element);
            textView.setCursorElement(element);
        });
    }

    static class Person {
        final String name;

        Person(String name) {
            this.name = name;
        }

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @SuppressWarnings("FieldCanBeLocal")
    private final Text.TextObserver textWatcher = new Text.TextObserver() {
        @Override
        public void onTextUpdated(String s, int start, int before, int count) {
            starts = 0;
            if (!TextTool.isNullOrEmpty(s)) {
                starts = helper.findTokenStart(s, s.length(), listContainer);
            }
            String inputText = textView.getText().substring(starts);
            if (starts == 0 || TextTool.isNullOrEmpty(inputText)) {
                listContainer.setVisibility(Component.HIDE);
            }
            if (!TextTool.isNullOrEmpty(inputText) && s.length() > 1) {
                String ss;
                if (starts != 0) {
                    ss = textView.getText().substring(starts - 1);
                } else {
                    ss = textView.getText().substring(starts);
                }
                switch (ss.charAt(0)) {
                    case '#':
                        if (isHashtag) {
                            setItemProvider(hashtagAdapter, inputText, ss.charAt(0));
                        } else {
                            listContainer.setVisibility(Component.HIDE);
                        }
                        break;
                    case '@':
                        if (isMention) {
                            setItemProvider(mentionAdapter, inputText, ss.charAt(0));
                        } else {
                            listContainer.setVisibility(Component.HIDE);
                        }
                        break;
                }
            }
        }
    };


    private void setItemProvider(ArrayProvider arrayProvider, String inputText, char type) {
        arrayProvider.clear();
        if (TextTool.isNullOrEmpty(inputText)) {
            return;
        }
        if (!isCustom) {
            if (type == '#') {
                if ("follow".indexOf(inputText) != -1) {
                    arrayProvider.add(new Person(HASHTAG1));
                }
                if ("followme".indexOf(inputText) != -1) {
                    arrayProvider.add(new Person(HASHTAG2));
                }
                if ("followmeorillkillyou".indexOf(inputText) != -1) {
                    arrayProvider.add(new Person(HASHTAG3));
                }
                if (listContainer.getItemProvider() != hashtagAdapter) {
                    listContainer.setItemProvider(arrayProvider);
                }
            } else {
                if ("dirtyhobo".indexOf(inputText) != -1) {
                    arrayProvider.add(new Person(MENTION1_USERNAME));
                }
                if ("hobo".indexOf(inputText) != -1) {
                    arrayProvider.add(new Person(MENTION2_USERNAME));
                }
                if ("hendraanggrian".indexOf(inputText) != -1) {
                    arrayProvider.add(new Person(MENTION3_USERNAME));
                }
                if (listContainer.getItemProvider() != mentionAdapter) {
                    listContainer.setItemProvider(arrayProvider);
                }
            }
        } else {
            if (type == '#') {
                if ("follow".indexOf(inputText) != -1) {
                    arrayProvider.add(new Hashtag(HASHTAG1));
                }
                if ("followme".indexOf(inputText) != -1) {
                    arrayProvider.add(new Hashtag(HASHTAG2, HASHTAG2_COUNT));
                }
                if ("followmeorillkillyou".indexOf(inputText) != -1) {
                    arrayProvider.add(new Hashtag(HASHTAG3, HASHTAG3_COUNT));
                }
                if (listContainer.getItemProvider() != hashtagAdapter) {
                    listContainer.setItemProvider(arrayProvider);
                }
            } else {
                if ("dirtyhobo".indexOf(inputText) != -1) {
                    arrayProvider.add(new Mention(MENTION1_USERNAME));
                }
                if ("hobo".indexOf(inputText) != -1) {
                    arrayProvider.add(new Mention(MENTION2_USERNAME, MENTION2_DISPLAYNAME));
                }
                if ("hendraanggrian".indexOf(inputText) != -1) {
                    arrayProvider.add(new Mention(MENTION3_USERNAME, MENTION3_DISPLAYNAME));
                }
                if (listContainer.getItemProvider() != mentionAdapter) {
                    listContainer.setItemProvider(arrayProvider);
                }
            }
        }
        if (arrayProvider.getCount() > 0) {
            listContainer.setVisibility(Component.VISIBLE);
        } else {
            listContainer.setVisibility(Component.HIDE);
        }
    }


    static class PersonAdapter extends SocialArrayAdapter<Person> {
        PersonAdapter(Context context) {
            super(context, ResourceTable.Layout_item_person_ohos);
        }

        @Override
        public Component getComponent(int position, Component convertView, ComponentContainer parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutScatter.getInstance(getContext())
                        .parse(ResourceTable.Layout_item_person_ohos, parent, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            Person item = getItem(position);
            if (item != null) {
                holder.textView.setText(item.name);
            }
            return convertView;
        }

        private static class ViewHolder {
            final Text textView;

            ViewHolder(Component view) {
                this.textView = (Text) view.findComponentById(ResourceTable.Id_textViewName);
            }
        }
    }

    /**
     * 初始化设置显示dialog
     */
    private void setShowDialog() {
        dialogView = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_dialog_select, null, false);
        Checkbox customAdapter = (Checkbox) dialogView.findComponentById(ResourceTable.Id_customAdapterItem);
        Checkbox hashtag = (Checkbox) dialogView.findComponentById(ResourceTable.Id_enableHashtagItem);
        Checkbox mention = (Checkbox) dialogView.findComponentById(ResourceTable.Id_enableMentionItem);
        Checkbox hyperlink = (Checkbox) dialogView.findComponentById(ResourceTable.Id_enableHyperlinkItem);
        DependentLayout textCustom = (DependentLayout) dialogView.findComponentById(ResourceTable.Id_textCustom);
        DependentLayout textHashtag = (DependentLayout) dialogView.findComponentById(ResourceTable.Id_textHashtag);
        DependentLayout textMention = (DependentLayout) dialogView.findComponentById(ResourceTable.Id_textMention);
        DependentLayout textHyperlink = (DependentLayout) dialogView.findComponentById(ResourceTable.Id_textHyperlink);
        customAdapter.setChecked(isCustom);
        hashtag.setChecked(isHashtag);
        mention.setChecked(isMention);
        hyperlink.setChecked(isHyperlink);

        textCustom.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (isCustom) {
                    isCustom = false;
                    hashtagAdapter = customHashtagAdapter;
                    mentionAdapter = customMentionAdapter;
                } else {
                    isCustom = true;
                    hashtagAdapter = defaultHashtagAdapter;
                    mentionAdapter = defaultMentionAdapter;
                }
                customAdapter.setChecked(isCustom);
                setRemoveDialog();
            }
        });

        textHashtag.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (isHashtag) {
                    isHashtag = false;
                } else {
                    isHashtag = true;
                }
                hashtag.setChecked(isHashtag);
                setRemoveDialog();
            }
        });

        textMention.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (isMention) {
                    isMention = false;
                } else {
                    isMention = true;
                }
                mention.setChecked(isMention);
                setRemoveDialog();
            }
        });

        textHyperlink.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (isHyperlink) {
                    isHyperlink = false;
                } else {
                    isHyperlink = true;
                }
                hyperlink.setChecked(isHyperlink);
                setRemoveDialog();
            }
        });
        popupDialog = new PopupDialog(getContext(), more1);
        popupDialog.setAlignment(LayoutAlignment.LEFT | LayoutAlignment.TOP);
        popupDialog.setCustomComponent(dialogView);
        popupDialog.setBackColor(Color.TRANSPARENT);
        popupDialog.setTransparent(true);
        popupDialog.setDialogListener(new BaseDialog.DialogListener() {
            @Override
            public boolean isTouchOutside() {
                setRemoveDialog();
                return false;
            }
        });
        popupDialog.show();
    }

    /**
     * 销毁dialog
     */
    private void setRemoveDialog() {
        dialogView = null;
        popupDialog.remove();
        popupDialog.destroy();
    }
}
